from django.shortcuts import render
import datetime, time, json, urllib.parse, os
from django.db.models import Q
from tools.methods import create_md5, create_spider
from django.core.paginator import Paginator
from django.forms.models import model_to_dict
from collect.website.models import WebsiteList
from tools.callback import api_callback, page_callback
from tools.result import HttpResponseCMD, Code, Message
from django.shortcuts import render, HttpResponse, redirect
from django.views.decorators.http import require_GET, require_POST
from tools.parameter import parse_parameter, check_parameter, match_parameter
from django.shortcuts import render


@require_GET
def home(request):
    return redirect('/website_list')


@require_GET
@parse_parameter
@match_parameter({
    'keyword': 'length[0-999999]',
    'page': 'range[0-999999]',
}, page_callback)
def open_website_list(request, parameter):
    """打开列表页"""
    params = {'keyword': '', 'page': 1}
    parameter.update(**params)
    if not parameter:
        query = WebsiteList.objects.all().order_by('-create_time').values()
    else:
        query = WebsiteList.objects.filter(
            Q(website_name__contains=parameter['keyword']) |
            Q(website_url__contains=parameter['keyword'])
        ).order_by('-create_time').values()
    paginator = Paginator(query, per_page=20)
    result_lis = paginator.get_page(parameter['page'])
    return render(request, 'website_list.html', {'website_lis': result_lis, 'parmas': parameter})


@require_GET
def open_create_website_html(request):
    """打开创建网站页"""
    return render(request, 'create_website.html', {})


@require_POST
@parse_parameter
@check_parameter({
    'website_name': 'length[0-999999]',
    'website_url': 'length[0-999999]',
    'isforeign': 'range[0-999999]',
    'website_type': 'range[0-999999]',
    'brand': 'length[0-999999]',
    'menu': 'length[0-999999]',
}, api_callback)
def create_website_config(request, parameter):
    """创建网站"""
    parameter['website_id'] = create_md5(urllib.parse.urlparse(parameter['website_url']).netloc)
    parameter['create_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    parameter['collect_status'], parameter['column_count'], parameter['crawl_count'] = 0, 0, 0
    if WebsiteList.objects.filter(website_id=parameter['website_id']).exists():
        return HttpResponseCMD(Code.success, Message.success, '网站已存在').to_response()
    try:
        WebsiteList.objects.create(**parameter)
        return HttpResponseCMD(Code.success, Message.success, '创建成功').to_response()
    except Exception as e:
        return HttpResponseCMD(Code.system_error, Message.system_error, e).to_response()


@require_GET
@parse_parameter
@check_parameter({
    'website_id': 'length[0-999999]',
    'collect_status': 'range[0-999999]',
}, api_callback)
def update_website_collect_status(request, parameter):
    """更新网站监控状态"""
    try:
        if parameter['collect_status'] == 1:
            path = os.getcwd().replace('\\', '/')
            create_spider(parameter['website_id'], path.replace('CrawlCenter', '') + 'CrawlCenterSpiders/CrawlCenterSpiders/spiders/')
        config = WebsiteList.objects.get(website_id=parameter['website_id'])
        config.collect_status = parameter['collect_status']
        config.save()
        return HttpResponseCMD(Code.success, Message.success, model_to_dict(config)).to_response()
    except Exception as e:
        return HttpResponseCMD(Code.system_error, Message.system_error, e).to_response()


@require_GET
@parse_parameter
@check_parameter({
    'website_id': 'length[0-999999]',
}, api_callback)
def delete_website_config(request, parameter):
    """删除网站"""
    try:
        WebsiteList.objects.filter(website_id=parameter['website_id']).delete()
        return HttpResponseCMD(Code.success, Message.success, '删除成功').to_response()
    except Exception as e:
        return HttpResponseCMD(Code.system_error, Message.system_error, e).to_response()


@require_GET
@parse_parameter
@check_parameter({
    'website_id': 'length[0-999999]',
}, page_callback)
def edit_website_config(request, parameter):
    """编辑网站"""
    config = WebsiteList.objects.get(website_id=parameter['website_id'])
    return render(request, 'edit_website.html', model_to_dict(config))


@require_POST
@parse_parameter
@match_parameter({
    'website_id': 'length[0-999999]',
    'website_name': 'length[0-999999]',
    'website_url': 'length[0-999999]',
    'isforeign': 'range[0-999999]',
    'website_type': 'range[0-999999]',
    'brand': 'length[0-999999]',
    'menu': 'length[0-999999]',
}, api_callback)
def update_website_config(request, parameter):
    try:
        config = WebsiteList.objects.get(website_id=parameter['website_id'])
        config.website_name = parameter['website_name']
        config.website_url = parameter['website_url']
        config.isforeign = parameter['isforeign']
        config.website_type = parameter['website_type']
        config.brand = parameter['brand']
        config.menu = parameter['menu']
        config.create_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        config.save()
        return HttpResponseCMD(Code.success, Message.success, '编辑成功').to_response()
    except Exception as e:
        return HttpResponseCMD(Code.system_error, Message.system_error, e).to_response()